#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 56, INF = 0x3f3f3f3f;

int mp[N][N];
int prim(int n)
{
   int d[N];
   bool st[N] = { false }; //刷新状态
   for (int i = 1; i <= n; i++)
   {
       d[i] = INF;
   }
   ///memset(d, 0x3f, sizeof d);
   int cnt = 0;
   for (int i = 0; i < n; i++)
   {
       int t = -1;
       for (int j = 1; j <= n; j++)
       {
           if (!st[j] && (t == -1 || d[t] > d[j])) t = j;
       }
       if (i > 0) cnt += d[t];
       for (int j = 1; j <= n; j++) d[j] = min(d[j], mp[t][j]);

       st[t] = true;
   }
   return cnt;
}


void solve(int n)
{
   int m;
   cin >> m;
   memset(mp, 0x3f, sizeof mp);
   while (m--)
   {
       int a, b, w;
       cin >> a >> b >> w;
       mp[a][b] = mp[b][a] = min(mp[a][b], w);
   }

   cout << prim(n) << '\n';
   return;
}


int main()
{
   ios::sync_with_stdio(0);
   cin.tie(0);
   cout.tie(0);

   int n;
   while (cin >> n)
   {
       if (n == 0) break;
       solve(n);
   }

   return 0;
}